import { TableRecordType, TableColumnType } from './types'
import { FormItemsType } from '@/components/CrudDialog/type'

export const removeIndex = (dataSource: TableRecordType[]) => {
  for (let i = 0; i < dataSource.length; i++) {
    if (dataSource[i].index) {
      delete dataSource[i].index
    }
  }
}
/**
 * 给操作栏 buutton 绑定点击事件
 * @param {*}  columns 表头
 * @param {*}  key 按钮的key
 * @param {*}  callback 点击事件
 * @returns
 */
export const bindButtonClickEvent = (columns: TableColumnType[], key: string, callback: (...args: any) => any) => {
  const button = columns.find((item: any) => item.key == 'button')
  if (button && button.group) {
    const targetButton = button.group.find((item: any) => item.key == key)
    if (targetButton) targetButton.click = callback
  }
}

/**
 * 给普通栏绑定点击事件
 * @param {*}  columns 表头
 * @param {*}  key 按钮的key
 * @param {*}  callback 点击事件
 * @returns
 */

export const bindClickEvent = (columns: TableColumnType[], key: string, callback: (...args: any[]) => any) => {
  const button = columns.find((item: any) => item.key == key)
  if (button) {
    button.click = callback
  }
}

/**
 * 给操作栏 添加 下拉选项等 | 事件
 * @param {*}  formItems 表单json
 * @param {*}  key 所选表单项的key
 * @param {*}  options 下拉选项
 * @param {*}  callback 点击事件
 * @tips   需要手动给options赋值null
 */
export const useForm = (formItems: FormItemsType[], key: string, options?: any, callback?: (...args: any[]) => any) => {
  const item = formItems.find((item: any) => item.key == key)
  if (!item) return

  if (options) {
    item.options = options
  }

  if (callback) {
    item[`${item.eventName}`] = callback
  }
}
